<template>
	<view class="content">
		<view class="user-welfare">
			<image src="https://wechat-pictures-1301970825.file.myqcloud.com/shop/regist/user-welfare.png"
				mode="aspectFill"></image>
		</view>
		<view class="box-content">
			<!-- 姓名 -->
			<view class="box">
				<view class="box-left">姓名</view>
				<view class="box-right">
					<input placeholder="请输入真实姓名" v-model="name" />
				</view>
			</view>
			<!-- 性别 -->
			<view class="box">
				<view class="box-left">性别</view>
				<view class="box-right">
					<view class="box-right-sex">
						<view @click="choose_sex(2)"
							:class="sex == 2 ? 'box-right-sex-box box-right-sex-box-active' : 'box-right-sex-box'">
							<image v-if="sex == 2" class="box-right-sex-box-icon" src="../../static/image/nv-active.png"
								mode=""></image>
							<image v-else class="box-right-sex-box-icon" src="../../static/image/nv.png" mode="">
							</image>
							女
						</view>
						<view @click="choose_sex(1)"
							:class="sex == 1 ? 'box-right-sex-box box-right-sex-box-active' : 'box-right-sex-box'">
							<image v-if="sex == 1" class="box-right-sex-box-icon"
								src="../../static/image/nan-active.png" mode=""></image>
							<image v-else class="box-right-sex-box-icon" src="../../static/image/nan.png" mode="">
							</image>
							男
						</view>
					</view>
				</view>
			</view>
			<!-- 出生日期 -->
			<view class="box">
				<view class="box-left">出生日期</view>
				<view class="box-right">
					<picker style="width: 100%;" mode="date" ref="opendata" :value="birthdayTwo" :start="startTime"
						:end="endTime" @change="bindDateChange">
						<view class="choose-date">{{birthday ? birthday : '请选择出生日期'}}</view>
					</picker>
				</view>
				<uni-icons type="forward"></uni-icons>
			</view>
			<!-- 手机号 -->
			<view class="box">
				<view class="box-left">手机号</view>
				<view class="box-right">
					<input placeholder="请输入本人手机号" type="number" maxlength="11" v-model="phone" />
				</view>
			</view>
		</view>
		<view class="form">
			<view class="input-item" v-if="!invitorCustomer && !inviterUserId">
				<view class="input-info">
					<view class="input-title">门店邀请码</view>
					<view class="input">
						<input type="number" :disabled="requestCode" v-model="code" placeholder="请输入门店邀请码" />
					</view>
				</view>
			</view>
			<view style="height: 80upx;line-height: 80upx;font-size: 32upx;color: #333;" v-if="inviterName">
				邀请人：{{ inviterName }}
			</view>
			<view style="height: 80upx;line-height: 80upx;font-size: 32upx;color: #333;" v-if="d_sheng">
				归属信息：{{ d_sheng }} - {{ d_shi }} - {{ deptName }}
			</view>
		</view>
		<view class="button" @click="submit()">提交</view>

		<view class="successBox" v-show="showNewYearSuccess">
			<view class="successBox-cover"></view>
			<view class="successBox-main">
				<view class="successBox-main_title">
					额外送您200积分
				</view>

				<view class="successBox-main_desc">
					积分当钱花！在人康下单任意产品可抵扣2元！
				</view>
				<view class="successBox-main_time">
					{{successTime}}s后自动消失
				</view>
				<view class="successBox-main_btn" @click="updateNewYearSuccess(false)">
					好的，我知道了
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadFile2
	} from "@/common/new_file.js";
	import {
		trackingHost,
		stateHost
	} from "@/common/config";
	export default {
		data() {
			return {
				avatar: '', // 头像
				name: '', // 姓名
				sex: 0, // 1男 2女
				birthday: '', // 出生年月日
				birthdayTwo: '1962-01-01',
				startTime: '1910-01-01',
				endTime: '2050-01-01',
				phone: '',
				province: '',
				city: '',
				district: '',

				requestCode: '',
				code: '',
				d_sheng: '',
				d_shi: '',
				deptName: '',
				type: 'answer', // answer 答题进来的 index 主页进来注册的
				source: null,
				storeId: null,
				invitorCustomer: "", //邀请顾客的unionid
				inviterName: "", //邀请人名称
				sourcePage: "",
				showNewYearSuccess: false,
				successTimer: null,
				successTime: 5,
				inviterUserId: '',
				registLinkId: ''
			}
		},
		async onLoad(res) {
			const {
				source: prevPageSource,
				sourcePage,
				invitorCode
			} = res;
			this.sourcePage = sourcePage;
			this.source = {
				tcm: 1,
				newPeopleTask: 3,
			} [sourcePage] || 2;
			this.prevPageSource = prevPageSource;
			if (res.type) {
				this.type = res.type;
			}
			console.log(invitorCode, res)
			this.code = invitorCode;
			this.d_sheng = decodeURIComponent(res.sheng || '');
			this.d_shi = decodeURIComponent(res.shi || '');
			this.deptName = decodeURIComponent(res.deptName || '');
			this.requestCode = res.requestCode;
			this.invitorCustomer = res.inviterUnionid || '';
			this.inviterName = decodeURIComponent(res.inviterName || '')
			// 店长端注册链接分享卡片来源
			if (this.type === 'registLink') {
				this.inviterUserId = res.inviterUserId;
				this.registLinkId = decodeURIComponent(res.registLinkId || '')
			}

			// 店长端注册链接二维码来源
			if (res.scene) {
				const scene = decodeURIComponent(res.scene)
				if (scene.includes('a=')) {
					const sceneInfo = scene.split('=')[1];
					const info = await this.$NoteApi.doRequest("get", "invitee/exchangeScene", {
						scene: sceneInfo
					})
					console.log('info', info)
					if (info.data.code == 200 && info.data.data) {
						this.code = info.data.data.storeInvitecode;
						this.d_sheng = info.data.data.sheng;
						this.d_shi = info.data.data.shi;
						this.deptName = info.data.data.deptName;
						this.inviterName = info.data.data.inviterName;
						this.inviterUserId = info.data.data.inviterUserId;
						this.registLinkId = info.data.data.registLinkId
					}
					this.type = 'registLink'
				}
			}
			// 判断链接是否有效
			if (this.registLinkId) {
				this.checkLink()
			}
			this.dadian()
		},
		onShow() {
			//获取用户token
			this.login()
		},
		methods: {
			findCus(event) {
				return this.$request("api/red/yzkj/findCus", {
						method: "GET",
						host: stateHost
					})
					.then(res => {
						const {
							storeId
						} = res;
						this.storeId = storeId;
						this.register(event);
					}).catch(error => {
						this.register(event)
					})
			},
			// 体测埋点
			register(event) {
				const {
					unionid,
					openid
				} = uni.getStorageSync("userInfo")
				const params = {
					oid: openid,
					uid: unionid,
					sid: this.storeId,
					ts: Date.parse(new Date()) / 1000,
					event,
					page: "register",
					source: this.source,
				}
				this.$request("event-tracking/user", {
						host: trackingHost,
						params
					})
					.catch(() => {})
			},
			// 获取入口权限
			getTaskEnterLimits() {
				return this.$request("marketing/user/activity/available", {
						params: {
							source: "RegisterSuccess",
							activityType: "New_People_Task"
						}
					})
					.then(data => data.result).catch(() => null)
			},

			//获取token
			login(isFromRegister) {
				// 获取微信code
				var _this = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						_this.check_login(loginRes.code, isFromRegister);
					},
					fail: (err) => {
						console.error('wx.login fail, reason:', err)
					}
				})
			},
			// 检测登录
			async check_login(code, isFromRegister) {
				var _this = this;
				var data = {
					code: code,
					requestCode: ''
				};
				try {
					const res = await this.$NoteApi.doRequest("get", "login", data);
					if (res.data.code == 0) {
						uni.setStorageSync("token", res.data.data.token)
						uni.setStorageSync("userInfo", res.data.data);

						await this.findCus(isFromRegister ? "register" : "impression");

						if (isFromRegister && this.sourcePage === "tcm") {
							uni.redirectTo({
								url: `/pages/physiqueTest/index?source=${this.prevPageSource}`
							});
							return;
						}
						if (isFromRegister && this.sourcePage === "newPeopleTask") {
							// 新人任务权限入口
							uni.redirectTo({
								url: `/pages/newPeopleTask/index?source=${this.prevPageSource}`
							});
							return;
						}

						if (res.data.data.isNew != 1) { //非新用户
							if (_this.type == 'index') { //跳转到首页
								uni.switchTab({
									url: '/pages/sindex/index',
								})
							} else if (_this.type == 'registLink') { // 店长端注册链接过来的
								if (res.data.data.source == 4) {
									if (!res.data.data.invitorInfo || res.data.data.invitorInfo.invitorUserId !== this
										.inviterUserId) {
										// 已注册，且邀请的员工不是当前分享链接的邀请员工，按照已经注册的处理
										this.handleRegisted();
									} else {
										// 是店长端注册
										this.handleInviterUser()
									}
								} else {
									// 其他渠道注册用户
									this.handleRegisted();
								}
							} else if (this.type === 'welfare') { // 门店福利页面
								this.handleInviterUser()
							} else if (this.invitorCustomer) { //拉新活动跳到添加健康顾问
								uni.navigateTo({
									url: '/pages/newMember/shopQcode?unionid=' + res.data.data.unionid
								})
							} else { //其他情况返回上一页
								setTimeout(function() {
									uni.navigateBack();
								}, 1500)
							}
						} else {
							if (this.type === 'registLink') {
								this.handleOnOffice();
							}
						}
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}

				} catch (error) {}
			},

			async handleInviterUser() {
				// TODO 如果是店长端注册判断邀请员工是否在职
				const onOfficeRes = await this.$NoteApi.doRequest("get", "inviter/inviterOnOffice", {
					inviteCode: `${this.code}`
				})
				if (onOfficeRes && (onOfficeRes.data.code == 0 || onOfficeRes.data.code == 200) && onOfficeRes.data
					.data) {
					// 已经注册，且邀请员工是当前链接邀请员工，且员工在职
					console.log('判断是否加好友')
					const addFriendRes = await this.$NoteApi.doRequest("get", "inviter/addFriend", {})
					if (addFriendRes.data.code == 0 || addFriendRes.data.code == 200) {
						if (addFriendRes.data.data) {
							// 已经添加好友
							uni.redirectTo({
								url: '/shopRegister/addSuccess/index?shopName=' + this.d_shi + this.deptName
							})
						} else {
							// 未添加好友
							uni.redirectTo({
								url: '/shopRegister/shopQrcode/index?inviteCode=' + this.code
							})
						}
					}
				} else {
					// 已注册，员工已离职
					this.handleUserExit();
				}
			},

			handleRegisted() {
				uni.showModal({
					title: '提示',
					content: '您已完成注册，点击确定回到首页',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.switchTab({
								url: '/pages/sindex/index',
							})
						}
					}
				})
			},

			// 店长端注册链接渠道，判断邀请员工是否在职，仅用于用户未注册状态时
			handleOnOffice() {
				console.log('handleOnOffice start')
				this.$NoteApi.doRequest("get", "inviter/inviterOnOffice", {
					inviteCode: `${this.code}`
				}).then(res => {
					console.log('handleOnOffice res', res)
					if (res.data.code == 0 || res.data.code == 200) {
						if (!res.data.data) {
							this.handleUserExit();
						}
					}
				})
			},

			handleUserExit() {
				uni.showModal({
					title: '提示',
					content: "当前链接已失效，请联系店长重新获取",
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.exitMiniProgram()
						}
					}
				})
			},

			//进入注册页面来源打点
			dadian() {
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				if (routes.length < 2) {
					var curRoute = ""
				} else {
					var curRoute = routes[routes.length - 2].route // 获取当前页面路由，也就是最后一个打开的页面路由
				}
				console.log('curRoute', curRoute)
				if (curRoute == 'videoNote/noteupload/noteupload') { //打卡笔记进入
					this.$dadian("noteupload")
				} else if (curRoute == 'pages/newAnswer/index') { //视频答题进入
					this.$dadian('newAnswer')
				} else { //自行进入
					this.$dadian("index")
				}
			},
			bindDateChange(e) {
				this.birthday = e.detail.value;
				return
			},
			// 获取地区
			bindRegionChange(e) {
				this.province = e.detail.value[0];
				this.city = e.detail.value[1];
				this.district = e.detail.value[2];
			},
			// 获取时间
			getTime(e) {
				this.birthday = e;
			},
			// 上传头像
			uploadImg() {
				var _this = this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						var filePath = res.tempFiles[0].path;
						var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
						uploadFile2(filePath, filename).then(res => {
							_this.avatar = 'https://' + res.Location.replace("cos.ap-beijing", "file");
						})
					}
				})
			},
			// 选择性别
			choose_sex(num) {
				this.sex = num;
			},
			// 检测链接是否生效
			async checkLink() {
				let res = await this.$NoteApi.doRequest("get", "registerManage/queryStatus", {
					linkId: this.registLinkId
				}, '', true);
				if (res.data.code === 0 && res.data.data === 0) {
					uni.showModal({
						title: '提示',
						content: '当前链接已失效，请联系店长重新获取',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.switchTab({
									url: '/pages/sindex/index',
								})
							}
						}
					})
				}
			},
			// 提交
			submit() {
				var title = '';
				if (this.name == '' || this.phone == '' || this.sex == 0 || this.birthday == '') {
					if (this.name == '') {
						uni.showToast({
							title: '请输入本人姓名!',
							icon: 'none'
						})
						return
					}
					if (this.phone == '') {
						uni.showToast({
							title: '请输入本人手机号!',
							icon: 'none'
						})
						return
					}
					
					if (this.sex == 0) {
						uni.showToast({
							title: '请选择性别!',
							icon: 'none'
						})
						return
					}
					if (this.birthday == '') {
						uni.showToast({
							title: '请选择出生日期!',
							icon: 'none'
						})
						return
					}
				}
				console.log('this.phone', this.phone);
				if (this.phone.trim().length !== 11) {
					uni.showToast({
						title: '手机号格式不正确!',
						icon: 'none'
					})
					return
				}
				var that = this;
				var data = {
					name: this.name,
					sex: this.sex == 0 ? '' : (this.sex == 1 ? '男' : '女'),
					birthday: this.birthday.trim(),
					phone: this.phone,
					invitorCode: this.code,
					requestCode: this.requestCode
				};
				//如果有邀请人id，就传入邀请人id
				if (this.invitorCustomer) data.invitorCustomer = this.invitorCustomer;
				// 注册链接
				if (this.registLinkId) data.registLinkId = this.registLinkId
				if (this.type === 'registLink') { // 店长端注册链接来源
					data.source = 4
				}
				if (this.type === 'welfare') {
					data.source = 5
				}

				that.$NoteApi.doRequest("post", "regist", data, 'json').then(res => {
					if (res.data.code == 0) {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
						//更新token，旧的token没有门店信息，如果不更新部分接口会报错
						uni.removeStorageSync('token');
						that.login(true);
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.successBox {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;

		&-cover {
			position: absolute;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background: rgba(0, 0, 0, .7);
		}

		&-main {
			width: 715rpx;
			height: 772rpx;
			background: url($uni-url+'/shop/newYearRecruit/bg_newYear_zhucecheng.png') 50% 50% / contain no-repeat;
			position: relative;
			z-index: 2;

			&_title {
				width: 100%;
				height: 72rpx;
				font-size: 56rpx;
				font-weight: 600;
				color: #FF3333;
				line-height: 72rpx;
				text-align: center;
				margin: 280rpx auto 0;
			}

			&_desc {
				width: 468rpx;
				height: 118rpx;
				font-size: 42rpx;
				font-weight: 500;
				color: #BA5B00;
				line-height: 59rpx;
				margin: 30rpx auto 0;
				text-align: center;
			}

			&_time {
				width: 300rpx;
				height: 28rpx;
				font-size: 28rpx;
				font-weight: 400;
				color: #BA5B00;
				line-height: 28rpx;
				margin: 72rpx auto 0;
				text-align: center;
			}

			&_btn {
				width: 430rpx;
				height: 116rpx;
				background: url($uni-url+'/shop/newYearRecruit/icon_btn_bg_newYear.png') 50% 50% / contain no-repeat;
				margin: 16rpx auto;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 27rpx 0 39rpx;
				font-size: 36rpx;
				font-weight: 500;
				color: #FFFFFF;
				box-sizing: border-box;
			}
		}
	}

	.uni-input {
		font-size: 32upx;
	}

	.select-region-text {
		font-size: 32upx;
	}

	.content {
		width: 100%;
		height: 100vh;
		background-color: #F7F7F7;
		box-sizing: border-box;
		/* padding-bottom: 60upx; */
		overflow: auto;
	}

	.top {
		width: 100%;
		height: 178upx;
		color: #fff;
		font-size: 36upx;
		text-align: center;
		box-sizing: border-box;
		padding-top: 34upx;
		font-weight: 500;
		background-color: #01B099;
		border-radius: 0upx 0upx 60upx 60upx;
	}

	.user-img {
		width: 686upx;
		height: 220upx;
		background-color: #fff;
		box-shadow: 0px 2upx 12upx 0px rgba(16, 61, 55, 0.36);
		border-radius: 16upx;
		margin: 0 auto;
		margin-top: -60upx;
		font-size: 36upx;
		color: #666;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.user-img image {
		width: 100upx;
		height: 100upx;
		border-radius: 50%;
		border: 2upx solid #ccc;
		margin-right: 40upx;
	}

	/* ----------------------------- */
	.box-content {
		width: 750upx;
		min-height: 10upx;
		background-color: #fff;
	}

	.box {
		width: 690upx;
		height: 160upx;
		margin: 0 auto;
		background-color: #fff;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		border-bottom: 2upx solid #E8E8E8;
	}

	.box-left {
		width: 220upx;
		font-size: 36upx;
		font-weight: 400;
		color: #333333;
	}

	.box-right {
		flex: 1;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.box-right input {
		width: 100%;
		height: 100%;
		font-size: 38upx;
	}

	.box-right-sex {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.box-right-sex-box {
		width: 180upx;
		height: 78upx;
		border-radius: 28upx;
		border: 3upx solid #ADADAD;
		margin-right: 60upx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 38upx;
		font-weight: 500;
		color: #666666;
	}

	.box-right-sex-box-icon {
		width: 40upx;
		height: 40upx;
		margin-right: 10upx;
	}

	.box-right-sex-box-active {
		border: none;
		background: linear-gradient(307deg, #45BE6D 0%, #3BD06C 100%);
		border-radius: 28upx;
		color: #fff;
	}

	.choose-date {
		width: 100%;
		height: 160upx !important;
		line-height: 160upx;
		font-size: 38upx;
	}

	.select-region-text {
		width: 100%;
		height: 160upx;
		line-height: 160upx;
	}

	/* ----------------------------- */
	.form {
		width: 100%;
		background-color: #fff;
		box-sizing: border-box;
		padding: 0upx 32upx;
	}

	.input-item {
		width: 100%;
		height: 160upx;
		border-bottom: 2upx solid #E8E8E8;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.input-info {
		display: flex;
	}

	.input-title {
		width: 220upx;
		font-size: 36upx;
		font-weight: 400;
		color: #333333;
	}

	.input input {
		font-size: 38upx;
	}

	.sex {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 200upx;
	}

	.sex-item {
		display: flex;
		align-items: center;
		font-size: 36upx;
	}

	.sex-item .xuanze {
		width: 28upx;
		height: 28upx;
		border-radius: 50%;
		border: 2upx solid #CCCCCC;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10upx;
	}

	.sex-item .xuanze view {
		width: 14upx;
		height: 14upx;
		background-color: #ccc;
		border-radius: 50%;
	}

	.button {
		width: 686upx;
		height: 104upx;
		text-align: center;
		line-height: 104upx;
		color: #fff;
		font-size: 40upx;
		font-weight: 500;
		margin: 60upx auto;
		border-radius: 52upx;
		background: #5CAE77;
	}

	.radio text {
		font-size: 32upx;
	}

	.user-welfare {
		width: 100%;
		height: 610upx;
		background-color: #fff;

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>